import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { FileItem } from '@/utils/api';
import api from '@/utils/api';
import { useThemeStore } from '@/stores/themeStore';

const RecycleBin: React.FC = () => {
  const themePreference = useThemeStore((state) => state.theme);
  const isDark = useMemo(() => {
    if (themePreference === 'dark') return true;
    if (themePreference === 'light') return false;
    return window.matchMedia('(prefers-color-scheme: dark)').matches;
  }, [themePreference]);
  const panelClass = isDark
    ? 'bg-slate-800 border border-slate-700 text-slate-100'
    : 'bg-white border border-gray-100 text-gray-800';

  const [files, setFiles] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState<Set<string>>(new Set());
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);

  // 加载回收站文件
  const loadTrashFiles = useCallback(async () => {
    setLoading(true);
    try {
      const response = await api.fileManager.getTrashFiles({
        page,
        limit: 20,
      });

      if (response.data) {
        setFiles(response.data.files);
        setTotal(response.data.total);
      }
    } catch (error) {
      console.error('加载回收站失败:', error);
    } finally {
      setLoading(false);
    }
  }, [page]);

  useEffect(() => {
    loadTrashFiles();
  }, [loadTrashFiles]);

  // 恢复文件
  const handleRestore = async (fileId: string) => {
    try {
      await api.fileManager.restoreFile(fileId);
      loadTrashFiles();
      setSelectedFiles(new Set());
    } catch (error) {
      console.error('恢复文件失败:', error);
      alert('恢复文件失败');
    }
  };

  // 彻底删除
  const handlePermanentDelete = async (fileId: string) => {
    if (!confirm('确定要彻底删除该文件吗？此操作不可恢复！')) {
      return;
    }

    try {
      await api.fileManager.permanentDelete(fileId);
      loadTrashFiles();
      setSelectedFiles(new Set());
    } catch (error) {
      console.error('彻底删除失败:', error);
      alert('彻底删除失败');
    }
  };

  // 批量恢复
  const handleBatchRestore = async () => {
    const fileIds = Array.from(selectedFiles);
    if (fileIds.length === 0) return;

    try {
      for (const fileId of fileIds) {
        await api.fileManager.restoreFile(fileId);
      }
      loadTrashFiles();
      setSelectedFiles(new Set());
    } catch (error) {
      console.error('批量恢复失败:', error);
      alert('批量恢复失败');
    }
  };

  // 批量彻底删除
  const handleBatchPermanentDelete = async () => {
    const fileIds = Array.from(selectedFiles);
    if (fileIds.length === 0) return;

    if (!confirm(`确定要彻底删除选中的 ${fileIds.length} 个文件吗？此操作不可恢复！`)) {
      return;
    }

    try {
      for (const fileId of fileIds) {
        await api.fileManager.permanentDelete(fileId);
      }
      loadTrashFiles();
      setSelectedFiles(new Set());
    } catch (error) {
      console.error('批量彻底删除失败:', error);
      alert('批量彻底删除失败');
    }
  };

  // 清空回收站
  const handleClearTrash = async () => {
    if (!confirm('确定要清空回收站吗？此操作将永久删除所有文件，不可恢复！')) {
      return;
    }

    try {
      await api.fileManager.clearTrash();
      loadTrashFiles();
      setSelectedFiles(new Set());
    } catch (error) {
      console.error('清空回收站失败:', error);
      alert('清空回收站失败');
    }
  };

  // 切换选中状态
  const toggleSelect = (fileId: string) => {
    const newSelected = new Set(selectedFiles);
    if (newSelected.has(fileId)) {
      newSelected.delete(fileId);
    } else {
      newSelected.add(fileId);
    }
    setSelectedFiles(newSelected);
  };

  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedFiles.size === files.length) {
      setSelectedFiles(new Set());
    } else {
      setSelectedFiles(new Set(files.map((f) => f._id)));
    }
  };

  // 获取文件图标
  const getFileIcon = (file: FileItem) => {
    const iconMap: Record<string, string> = {
      image: '🖼️',
      video: '🎬',
      audio: '🎵',
      document: '📄',
      other: '📦',
    };
    return iconMap[file.category] || '📄';
  };

  // 获取删除天数的颜色
  const getDaysColor = (days: number) => {
    if (days >= 6) return isDark ? 'text-red-400' : 'text-red-600';      // 最后1天，红色警告
    if (days >= 5) return isDark ? 'text-orange-400' : 'text-orange-600';   // 最后2天，橙色
    if (days >= 3) return isDark ? 'text-yellow-300' : 'text-yellow-600';   // 最后4天，黄色提示
    return isDark ? 'text-slate-300' : 'text-gray-600';
  };

  const pageClass = isDark
    ? 'h-full flex flex-col bg-slate-900 text-slate-100'
    : 'h-full flex flex-col bg-gray-50 text-gray-900'

  return (
    <div className={`${pageClass} transition-colors`}>
      {/* 头部 */}
      <div className={`${panelClass} px-6 py-4 transition-colors`}>
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-800 dark:text-slate-100 flex items-center gap-2">
              <span>🗑️</span>
              回收站
            </h1>
            <p className="text-sm text-gray-500 dark:text-slate-400 mt-1">
              共 {total} 个已删除文件 · 文件将在7天后自动清理
            </p>
          </div>

          {/* 操作按钮 */}
          <div className="flex gap-2">
            {selectedFiles.size > 0 && (
              <>
                <button
                  onClick={handleBatchRestore}
                  className="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
                >
                  恢复选中 ({selectedFiles.size})
                </button>
                <button
                  onClick={handleBatchPermanentDelete}
                  className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
                >
                  彻底删除 ({selectedFiles.size})
                </button>
              </>
            )}
            {total > 0 && (
              <button
                onClick={handleClearTrash}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
              >
                清空回收站
              </button>
            )}
          </div>
        </div>
      </div>

      {/* 文件列表 */}
      <div className="flex-1 overflow-y-auto p-6">
        {loading ? (
          <div className="flex items-center justify-center h-64">
            <div className="text-gray-500 dark:text-slate-400">加载中...</div>
          </div>
        ) : files.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-64 text-gray-400 dark:text-slate-500">
            <span className="text-6xl mb-4">🗑️</span>
            <p className="text-lg">回收站为空</p>
            <p className="text-sm mt-2">删除的文件会出现在这里</p>
          </div>
        ) : (
          <div className={`${panelClass} rounded-lg shadow-sm overflow-hidden transition-colors`}>
            <table className="w-full">
              <thead className={`${isDark ? 'bg-slate-700/80 text-slate-200' : 'bg-gray-100 text-gray-700'} border-b ${isDark ? 'border-slate-600' : 'border-gray-200'}`}>
                <tr>
                  <th className="px-6 py-3 text-left">
                    <input
                      type="checkbox"
                      checked={selectedFiles.size === files.length && files.length > 0}
                      onChange={toggleSelectAll}
                      className="w-4 h-4"
                    />
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-200 uppercase">文件名</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-200 uppercase">大小</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-200 uppercase">删除时间</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-200 uppercase">剩余天数</th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-slate-200 uppercase">操作</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-slate-700">
                {files.map((file) => (
                  <tr
                    key={file._id}
                    className={`hover:bg-gray-50 dark:hover:bg-slate-700/40 ${
                      selectedFiles.has(file._id) ? 'bg-blue-50 dark:bg-blue-500/10' : ''
                    }`}
                  >
                    <td className="px-6 py-4">
                      <input
                        type="checkbox"
                        checked={selectedFiles.has(file._id)}
                        onChange={() => toggleSelect(file._id)}
                        className="w-4 h-4"
                      />
                    </td>
                    <td className="px-6 py-4 flex items-center gap-3">
                      <span className="text-2xl">{getFileIcon(file)}</span>
                      <span className="text-sm text-gray-800 dark:text-slate-100 truncate max-w-md" title={file.filename}>
                        {file.filename}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-600 dark:text-slate-300">
                      {file.sizeFormatted || formatFileSize(file.size)}
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-600 dark:text-slate-300">
                      {new Date(file.deletedAt!).toLocaleString()}
                    </td>
                    <td className="px-6 py-4 text-sm">
                      <span className={getDaysColor(file.daysInTrash || 0)}>
                        {7 - (file.daysInTrash || 0)} 天
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handleRestore(file._id)}
                          className="px-3 py-1 text-xs bg-green-500 text-white rounded hover:bg-green-600"
                        >
                          恢复
                        </button>
                        <button
                          onClick={() => handlePermanentDelete(file._id)}
                          className="px-3 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600"
                        >
                          彻底删除
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* 分页 */}
        {total > 20 && (
          <div className="mt-6 flex justify-center gap-2">
            <button
              onClick={() => setPage(page - 1)}
              disabled={page === 1}
              className={`px-4 py-2 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors ${
                isDark
                  ? 'bg-slate-800 border border-slate-700 text-slate-200 hover:bg-slate-700'
                  : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50'
              }`}
            >
              上一页
            </button>
            <span
              className={`px-4 py-2 rounded-lg border transition-colors ${
                isDark ? 'bg-slate-800 border-slate-700 text-slate-200' : 'bg-white border-gray-300 text-gray-700'
              }`}
            >
              {page} / {Math.ceil(total / 20)}
            </span>
            <button
              onClick={() => setPage(page + 1)}
              disabled={page >= Math.ceil(total / 20)}
              className={`px-4 py-2 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors ${
                isDark
                  ? 'bg-slate-800 border border-slate-700 text-slate-200 hover:bg-slate-700'
                  : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50'
              }`}
            >
              下一页
            </button>
          </div>
        )}
      </div>

      {/* 提示信息 */}
      <div className="bg-yellow-50 dark:bg-amber-500/10 border-t border-yellow-200 dark:border-amber-500/40 px-6 py-3 transition-colors">
        <div className="flex items-center gap-2 text-sm text-yellow-800 dark:text-amber-200">
          <span>⚠️</span>
          <span>温馨提示：回收站中的文件将在7天后自动永久删除，请及时恢复重要文件。</span>
        </div>
      </div>
    </div>
  );
};

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
};

export default RecycleBin;

